import axios from 'axios';
type AxiosInstance = ReturnType<typeof axios.create>;
import useUserStore from '../store/userStore';

/**
 * API 服务工具类
 * 封装与后端 API 的通信方法
 */
class ApiService {
  private axiosInstance: AxiosInstance;
  
  constructor() {
    // 创建 Axios 实例
    this.axiosInstance = axios.create({
      baseURL: process.env.NEXT_PUBLIC_API_BASE_URL || '',
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json',
      },
    });
    
    // 请求拦截器
    this.axiosInstance.interceptors.request.use(
      (config) => {
        const userStore = useUserStore.getState();
        if (userStore.user.token) {
          config.headers.Authorization = `Bearer ${userStore.user.token}`;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
    
    // 响应拦截器
    this.axiosInstance.interceptors.response.use(
      (response) => {
        return response.data;
      },
      (error) => {
        // 统一错误处理
        if (error.response?.status === 401) {
          const userStore = useUserStore.getState();
          userStore.logout();
          window.location.href = '/login';
        }
        return Promise.reject(error);
      }
    );
  }
  
  /**
   * 发送 GET 请求
   * @param endpoint API 端点路径
   * @returns Promise 解析为响应数据
   */
  async get<T>(endpoint: string): Promise<T> {
    return this.axiosInstance.get<T>(endpoint);
  }
  
  /**
   * 发送 POST 请求
   * @param endpoint API 端点路径
   * @param data 要发送的数据
   * @returns Promise 解析为响应数据
   */
  async post<T, D = unknown>(endpoint: string, data: D): Promise<T> {
    return this.axiosInstance.post<T>(endpoint, data);
  }
  
  /**
   * 发送 PUT 请求
   * @param endpoint API 端点路径
   * @param data 要发送的数据
   * @returns Promise 解析为响应数据
   */
  async put<T, D = unknown>(endpoint: string, data: D): Promise<T> {
    return this.axiosInstance.put<T>(endpoint, data);
  }
  
  /**
   * 发送 DELETE 请求
   * @param endpoint API 端点路径
   * @returns Promise 解析为响应数据
   */
  async delete<T>(endpoint: string): Promise<T> {
    return this.axiosInstance.delete<T>(endpoint);
  }
}

// 导出单例实例
const apiService = new ApiService();
export default apiService;